package org.planaz.campusvoting.service.impl;

import cn.hutool.core.util.RandomUtil;
import jakarta.annotation.Resource;
import org.planaz.campusvoting.common.enums.EmailTypeEnum;
import org.planaz.campusvoting.common.result.Result;
import org.planaz.campusvoting.common.result.Results;
import org.planaz.campusvoting.service.EmailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class EmailServiceImpl implements EmailService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    JavaMailSender javaMailSender;

    @Override
    public Result<?> sendEmail(String email, String type) {
        Date now = new Date();
        String code = stringRedisTemplate.opsForValue().get(email+":"+type);
        if(code != null){
            return Results.failure("-1","您的验证码依然有效，请勿重复请求");
        }
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom("1781088254@qq.com");
        message.setTo(email);
        message.setSentDate(now);
        code= RandomUtil.randomNumbers(4);
        stringRedisTemplate.opsForValue().set(email+":"+type,code,5*60,java.util.concurrent.TimeUnit.SECONDS);
        EmailTypeEnum emailType = EmailTypeEnum.getEnum(type);
        message.setSubject("【"+emailType.getName()+"验证码】");
        message.setText("您本次的验证码是："+code+"，有效期为五分钟。请妥善保管，切勿泄露");
        javaMailSender.send(message);
        return Results.success(emailType.getName()+"验证码发送成功");
    }
}
